﻿#include "DemandController.h"

DemandController* DemandController::create(unsigned int demandId){
	DemandController* me=new DemandController(demandId);
	if(me&&me->init()){
		me->autorelease();

		return me;
	} else{
		delete me;
		me=nullptr;

		return nullptr;
	}
}

DemandController::DemandController(unsigned int demandId){
	this->demandId=demandId;
	paymentV.pushBack(new CAValue("支付宝"));
	paymentV.pushBack(new CAValue("微信"));
}

DemandController::~DemandController(){}

void DemandController::viewDidLoad(){
	CAView* view=this->getView();
	this->setNavigationBarItem(CANavigationBarItem::create("发布需求"));
	if(demandId>0){
		sendHttp(view, "/api/appDemandInfo", obj2str("demandId=%u", demandId), CALLBACK_BIND_1(DemandController::fillData, this));
	}
	CAScrollView* scrollView=CAScrollView::createWithLayout(DLayoutFill);
	scrollView->setBounceHorizontal(false);
	scrollView->setHorizontalScrollEnabled(false);
	scrollView->setShowsHorizontalScrollIndicator(false);
	scrollView->setViewSize(DSize(view->getBounds().size.width, 1800));
	view->addSubview(scrollView);
	CALabel* title=CALabel::createWithLayout(DLayout(DHorizontalLayout_L_W(10, 200), DVerticalLayout_T_H(20, 50)));
	title->setText("需求信息");
	title->setFontSize(50);
	title->setColor(ccc4(77, 77, 77, 255));
	scrollView->addSubview(title);

	CAView* subviews=CAView::createWithLayout(DLayout(DHorizontalLayoutFill, DVerticalLayout_T_H(90, 1210)));
	subviews->enabledBottomShadow(true);
	CAView* subview=getSubview();
	subview->addSubview(getLabel("联系人"));
	person=getTextField();
	person->setPlaceHolderText("请输入姓名");
	subview->addSubview(person);
	subviews->addSubview(subview);
	subview=getSubview();
	subview->addSubview(getLabel("联系电话"));
	phone=getTextField();
	phone->setPlaceHolderText("请输入联系方式");
	subview->addSubview(phone);
	subviews->addSubview(subview);
	subview=getSubview();
	subview->addSubview(getLabel("产品品类"));
	category=getTextField();
	category->setPlaceHolderText("请选择产品品类");
	category->onShouldBeginEditing([&]{
		sendHttp(this->getView(), "/api/appSpecies/appQueryList", "{\"type\":0}", CALLBACK_BIND_1(DemandController::speciesData, this), CAHttpRequest::Type::Post, true);

		return false;
	});
	subview->addSubview(category);
	subviews->addSubview(subview);
	subview=getSubview();
	subview->addSubview(getLabel("产品名称"));
	categoryName=getTextField();
	categoryName->setPlaceHolderText("请选择产品名称");
	categoryName->onShouldBeginEditing([&]{
		sendHttp(this->getView(), "/api/appSpecies/appQueryList", "{\"type\":0}", CALLBACK_BIND_1(DemandController::speciesData, this), CAHttpRequest::Type::Post, true);

		return false;
	});
	subview->addSubview(categoryName);
	subviews->addSubview(subview);
	subview=getSubview();
	subview->addSubview(getLabel("产品规格"));
	boutique=CACheckbox::createWithLayout(DLayout(DHorizontalLayout_L_W(140, 200), DVerticalLayout_T_H(20, 54)), CACheckbox::Type::RoundedRect);
	boutique->setTitleStateNormal("精品");
	boutique->setTitleColorStateSelected(themeColor);
	boutique->setTarget([&](bool var){
		if(var){
			specifications="精品";
			currency->setIsOn(false);
		}else{
			boutique->setIsOn(true);
		}
	});
	subview->addSubview(boutique);
	currency=CACheckbox::createWithLayout(DLayout(DHorizontalLayout_L_W(350, 200), DVerticalLayout_T_H(20, 54)), CACheckbox::Type::RoundedRect);
	currency->setIsOn(true);
	currency->setTitleStateNormal("通货");
	currency->setTitleColorStateSelected(themeColor);
	currency->setTarget([&](bool var){
		if(var){
			specifications="通货";
			boutique->setIsOn(false);
		}else{
			currency->setIsOn(true);
		}
	});
	subview->addSubview(currency);
	subviews->addSubview(subview);
	subview=getSubview();
	subview->addSubview(getLabel("产品价格"));
	price=getTextField();
	price->setKeyboardType(CATextField::KeyboardType::NumberPad);
	price->setPlaceHolderText("请输入产品价格");
	price->onShouldEndEditing([&]{
		if(!(price->getText().empty())&&!(quantity->getText().empty())){
			deposit=atof(price->getText().c_str())*atof(quantity->getText().c_str())*0.3;
			money->setText(obj2str("%.2f", deposit));
		}

		return true;
	});
	subview->addSubview(price);
	subviews->addSubview(subview);
	subview=getSubview();
	subview->addSubview(getLabel("需求数量"));
	quantity=getTextField();
	quantity->setKeyboardType(CATextField::KeyboardType::NumberPad);
	quantity->setPlaceHolderText("请输入需求数量(公斤)");
	quantity->onShouldEndEditing([&]{
		if(!(price->getText().empty())&&!(quantity->getText().empty())){
			deposit=atof(price->getText().c_str())*atof(quantity->getText().c_str())*0.3;
			money->setText(obj2str("%.2f", deposit));
		}

		return true;
	});
	subview->addSubview(quantity);
	subviews->addSubview(subview);
	subview=getSubview();
	subview->addSubview(getLabel("交割地区"));
	receiveArea=getTextField();
	receiveArea->setPlaceHolderText("请选择交割地区");
	receiveArea->onShouldBeginEditing([&]{
		area="receive";
		sendHttp(this->getView(), "/api/dept/allAsTree", "", CALLBACK_BIND_1(DemandController::addressData, this));

		return false;
	});
	subview->addSubview(receiveArea);
	subviews->addSubview(subview);
	subview=getSubview();
	subview->addSubview(getLabel("详细地址"));
	location=getTextField();
	location->setPlaceHolderText("请输入您的详细地址(最多20个字)");
	subview->addSubview(location);
	subviews->addSubview(subview);
	subview=getSubview();
	subview->addSubview(getLabel("产品产地"));
	areaName=getTextField();
	areaName->setPlaceHolderText("请选择产品产地");
	areaName->onShouldBeginEditing([&]{
		area="areaName";
		sendHttp(this->getView(), "/api/dept/allAsTree", "", CALLBACK_BIND_1(DemandController::addressData, this));

		return false;
	});
	subview->addSubview(areaName);
	subviews->addSubview(subview);
	subview=getSubview();
	subview->addSubview(getLabel("装货时间"));
	supplyingTime=getTextField();
	supplyingTime->setPlaceHolderText("请选择装货时间");
	supplyingTime->onShouldBeginEditing([&]{
		CADatePickerView* pickerView=getDatePicker(this->getView());
		pickerView->onSelectRow([&](const tm& tm){
			supplyingTime->setText(obj2str("%d-%02d-%02d", (tm.tm_year+1900), (tm.tm_mon+1), tm.tm_mday));
		});
		string dates=supplyingTime->getText();
		if(dates.length()>0){
			CAScheduler::getScheduler()->scheduleOnce([=](float interval){
				pickerView->setDate(atoi(dates.substr(0, 4).c_str()), atoi(dates.substr(5, 2).c_str()), atoi(dates.substr(8, 2).c_str()), false);
			}, "selectDate", pickerView, 0);
		}

		return false;
	});
	subview->addSubview(supplyingTime);
	subviews->addSubview(subview);
	subview=getSubview();
	subview->addSubview(getLabel("备注"));
	remark=getTextField();
	remark->setPlaceHolderText("例: 产品包装等");
	subview->addSubview(remark);
	subviews->addSubview(subview);
	scrollView->addSubview(subviews);
	subviews=CAView::createWithLayout(DLayout(DHorizontalLayoutFill, DVerticalLayout_T_B(1330, 0)));
	subviews->enabledTopShadow(true);
	CALabel* bond=CALabel::createWithLayout(DLayout(DHorizontalLayout_L_W(10, 260), DVerticalLayout_T_H(30, 50)));
	bond->setText("支付保证金");
	bond->setFontSize(50);
	bond->setColor(ccc4(77, 77, 77, 255));
	subviews->addSubview(bond);
	money=CALabel::createWithLayout(DLayout(DHorizontalLayout_L_W(300, 260), DVerticalLayout_T_H(30, 50)));
	money->setText(obj2str("￥%.2f", deposit));
	money->setFontSize(50);
	money->setColor(ccc4(210, 14, 14, 255));
	subviews->addSubview(money);
	CALabel* explain=CALabel::createWithLayout(DLayout(DHorizontalLayout_L_W(10, 260), DVerticalLayout_T_H(90, 20)));
	explain->setText("定金说明：交易总额的30%");
	explain->setFontSize(20);
	explain->setColor(ccc4(153, 153, 153, 255));
	subviews->addSubview(explain);
	CALabel* method=CALabel::createWithLayout(DLayout(DHorizontalLayout_L_W(10, 260), DVerticalLayout_T_H(150, 30)));
	method->setText("支付方式");
	method->setFontSize(30);
	method->setColor(ccc4(77, 77, 77, 255));
	subviews->addSubview(method);
	payments=CALabel::createWithLayout(DLayout(DHorizontalLayout_R_W(10, 260), DVerticalLayout_T_H(150, 30)));
	payments->setText("支付宝");
	payments->setFontSize(30);
	payments->setColor(ccc4(77, 77, 77, 255));
	payments->setTextAlignment(CATextAlignment::Center);
	payments->setVerticalTextAlignmet(CAVerticalTextAlignment::Center);
	CAImageView* advance=CAImageView::createWithLayout(DLayout(DHorizontalLayout_R_W(0, 16), DVerticalLayout_H_C(28, 0.5)));
	advance->setImage(CAImage::create("img/advance.png"));
	payments->addSubview(advance);
	payments->onTouchBegan([&](CATouch* touch, CAEvent* event){
		CAPickerView* pickerView=getPicker(this->getView());
		pickerView->onWidthForComponent([&](unsigned int component){
			return this->getView()->getBounds().size.width;
		});
		pickerView->onTitleForRow([&](unsigned int row, unsigned int component){
			return paymentV.at(row)->asString();
		});
		pickerView->onNumberOfRowsInComponent([&](unsigned int component){
			return paymentV.size();
		});
		pickerView->onDidSelectRow([&](unsigned int row, unsigned int component){
			payments->setText(paymentV.at(row)->asString());
		});
		if(payments->getText().length()>0){
			CAScheduler::getScheduler()->scheduleOnce([=](float interval){
				CAValue* val=nullptr;
				for(int i=0, size=paymentV.size(); i<size; ++i){
					val=paymentV.at(i);
					if(val->asString().compare(payments->getText())==0){
						pickerView->selectRow(i, 0);
						break;
					}
				}
			}, "selectPayment", pickerView, 0);
		}

		return true;
	});
	subviews->addSubview(payments);
	subview=getSubview();
	CAButton* btn=CAButton::createWithLayout(DLayout(DHorizontalLayout_W_C(300, 0.5), DVerticalLayout_T_H(300, 100)), CAButton::Type::RoundedRect);
	btn->setTitleFontSize(50);
	btn->setTitleForState(CAControl::State::Normal, "提   交");
	btn->setTitleColorForState(CAControl::State::Normal, CAColor4B::WHITE);
	btn->setBackgroundImageForState(CAControl::State::Normal, CAImage::createWithColor4B(themeColor), true);
	btn->addTarget([&]{
		CSJson::Value paras;
		paras["demandId"]=demandId;
		paras["person"]=person->getText();
		paras["phone"]=phone->getText();
		paras["category"]=category->getText();
		paras["categoryName"]=categoryName->getText();
		paras["specifications"]=specifications;
		paras["price"]=price->getText();
		paras["quantity"]=quantity->getText();
		paras["receiveAreaCode"]=receiveAreaCode;
		paras["receiveArea"]=receiveArea->getText();
		paras["location"]=location->getText();
		paras["areaCode"]=areaCode;
		paras["areaName"]=areaName->getText();
		paras["supplyingTime"]=supplyingTime->getText();
		paras["remark"]=remark->getText();
		paras["deposit"]=deposit;
		paras["payment"]=payment;
		CSJson::FastWriter writer;
		CCLog("%s", writer.write(paras).c_str());
		getAlert(this->getView(), "保存成功");
	}, CAButton::Event::TouchDown);
	subviews->addSubview(btn);
	scrollView->addSubview(subviews);
}

void DemandController::fillData(const string& data){
	CSJson::Reader reader;
	CSJson::Value value;
	bool flag=reader.parse(data, value);
	if(!flag){
		getAlert(this->getView(), "数据解析异常, 请稍后重试");

		return;
	}
	CSJson::Value datas=value["content"][0];
	demandId=datas["demandId"].asUInt();
	person->setText(datas["person"].asCString());
	phone->setText(datas["phone"].asCString());
	category->setText(datas["category"].asCString());
	categoryName->setText(datas["categoryName"].asCString());
	specifications=datas["specifications"].asCString();
	if(specifications.compare("通货")==0){
		boutique->setIsOn(false);
	} else{
		currency->setIsOn(true);
	}
	price->setText(obj2str("%.2f", datas["price"].asInt()/100.0));
	quantity->setText(obj2str("%d", datas["quantity"].asInt()));
	receiveArea->setText(datas["receiveArea"].asCString());
	location->setText(datas["location"].asCString());
	areaCode=atoi(datas["areaCode"].asCString());
	areaName->setText(datas["areaName"].asCString());
	supplyingTime->setText(datas["supplyingTime"].asCString());
	remark->setText(datas["remark"].asCString());
	deposit=datas["deposit"].asDouble()/100.0;
	money->setText(obj2str("￥%.2f", deposit));
	payment=datas["payment"].asInt();
	payments->setText(paymentV.at(payment)->asString());
}

void DemandController::speciesData(const string& data){
	CSJson::Reader reader;
	CSJson::Value datas;
	bool flag=reader.parse(data, datas);
	if(!flag){
		getAlert(this->getView(), "数据解析异常, 请稍后重试");

		return;
	}
	speciesDatas=datas["content"];
	CAPickerView* pickerView=getPicker(this->getView());
	pickerView->onWidthForComponent([&](unsigned int component){
		return this->getView()->getBounds().size.width;
	});
	pickerView->onTitleForRow([&](unsigned int row, unsigned int component){
		return speciesDatas[row]["speciesName"].asCString();
	});
	pickerView->onNumberOfRowsInComponent([&](unsigned int component){
		return speciesDatas.size();
	});
	pickerView->onDidSelectRow([&](unsigned int row, unsigned int component){
		category->setText(obj2str("%u", speciesDatas[row]["speciesId"].asUInt()));
		categoryName->setText(speciesDatas[row]["speciesName"].asCString());
	});
	if(categoryName->getText().length()>0){
		CAScheduler::getScheduler()->scheduleOnce([=](float interval){
			std::string val=nullptr;
			for(int i=0, size=speciesDatas.size(); i<size; ++i){
				val=speciesDatas[i]["speciesName"].asString();
				if(val.compare(categoryName->getText())==0){
					pickerView->selectRow(i, 0);
					break;
				}
			}
		}, "selectSpecies", pickerView, 0);
	}
}

void DemandController::addressData(const string& data){
	CSJson::Reader reader;
	CSJson::Value provinceDatas;
	bool flag=reader.parse(data, provinceDatas);
	if(!flag){
		getAlert(this->getView(), "数据解析异常, 请稍后重试");

		return;
	}
	unsigned int III=0;
	if(receiveAreaCode==0&&area.compare("receive")==0){
		I=0;
		II=0;
		cityDatas=provinceDatas[0]["children"];
		countyDatas=cityDatas[0]["children"];
		const char* province=provinceDatas[0]["name"].asCString();
		const char* city=cityDatas[0]["name"].asCString();
		const char* county=countyDatas[0]["name"].asCString();
		receiveAreaCode=countyDatas[0]["id"].asUInt();
		receiveArea->setText(obj2str("%s%s%s", province, city, county));
	}else if(areaCode==0&&area.compare("areaName")==0){
		I=0;
		II=0;
		cityDatas=provinceDatas[0]["children"];
		countyDatas=cityDatas[0]["children"];
		const char* province=provinceDatas[0]["name"].asCString();
		const char* city=cityDatas[0]["name"].asCString();
		const char* county=countyDatas[0]["name"].asCString();
		areaCode=countyDatas[0]["id"].asUInt();
		areaName->setText(obj2str("%s%s%s", province, city, county));
	}else{
		unsigned int provinceCode=0;
		unsigned int cityCode=0;
		if(area.compare("receive")==0){
			provinceCode=receiveAreaCode-receiveAreaCode%10000;
			cityCode=receiveAreaCode-receiveAreaCode%100;
		} else if(area.compare("areaName")==0){
			provinceCode=areaCode-areaCode%10000;
			cityCode=areaCode-areaCode%100;
		}
		for(int i=0, isize=provinceDatas.size(); i<isize; ++i){
			if(provinceCode==provinceDatas[i]["id"].asUInt()){
				cityDatas=provinceDatas[i]["children"];
				for(int j=0, jsize=cityDatas.size(); j<jsize; j++){
					if(cityCode==cityDatas[j]["id"].asUInt()){
						countyDatas=cityDatas[j]["children"];
						for(int k=0, ksize=countyDatas.size(); k<ksize; k++){
							if(areaCode==countyDatas[k]["id"].asUInt()){
								I=i;
								II=j;
								III=k;
								goto RenderView;
							}
						}
					}
				}
			}
		}
	}

RenderView:
	CAView* view=this->getView();
	CAView* subview=CAView::createWithLayout(DLayout(DHorizontalLayoutFill, DVerticalLayout_B_H(0, 500)));
	subview->setColor(ccc4(190, 190, 190, 255));
	subview->setZOrder(50);
	view->addSubview(subview);
	CAButton* btn=CAButton::createWithLayout(DLayout(DHorizontalLayout_R_W(0, 120), DVerticalLayout_T_H(0, 100)), CAButton::Type::Custom);
	btn->setTitleForState(CAControl::State::Normal, "确定");
	btn->setTitleFontSize(60);
	btn->setTitleColorForState(CAControl::State::Normal, themeColor);
	btn->addTarget([=]{
		subview->removeAllSubviews();
		view->removeSubview(subview);
	}, CAButton::Event::TouchUpInSide);
	subview->addSubview(btn);
	float width=subview->getBounds().size.width/3;
	//省
	CAPickerView* provinceView=CAPickerView::createWithLayout(DLayout(DHorizontalLayout_L_W(0, width), DVerticalLayout_T_H(100, 400)));
	provinceView->setFontSizeNormal(40);
	provinceView->setBackgroundImage(CAImage::createWithColor4B(ccc4(190, 190, 190, 255)));
	provinceView->onHeightForComponent([](unsigned int component){
		return 80;
	});
	provinceView->onViewForSelected([](unsigned int component, DSize size){
		return CAView::createWithColor(themeColor);
	});
	provinceView->onTitleForRow([=](unsigned int row, unsigned int component){
		return provinceDatas[row]["name"].asCString();
	});
	provinceView->onWidthForComponent([=](unsigned int component){
		return this->getView()->getBounds().size.width;
	});
	provinceView->onNumberOfRowsInComponent([=](unsigned int component){
		return provinceDatas.size();
	});
	provinceView->onDidSelectRow([=](unsigned int row, unsigned int component){
		I=row;
		cityDatas=provinceDatas[row]["children"];
		countyDatas=cityDatas[0]["children"];
		const char* province=provinceDatas[row]["name"].asCString();
		const char* city=cityDatas[0]["name"].asCString();
		const char* county=countyDatas[0]["name"].asCString();
		if(area.compare("receive")==0){
			receiveAreaCode=countyDatas[0]["id"].asUInt();
			receiveArea->setText(obj2str("%s%s%s", province, city, county));
		}else if(area.compare("areaName")==0){
			areaCode=countyDatas[0]["id"].asUInt();
			areaName->setText(obj2str("%s%s%s", province, city, county));
		}
		if(cityView!=nullptr){
			cityView->reloadAllComponents();
			countyView->reloadAllComponents();
		}
	});
	subview->addSubview(provinceView);
	if(I>0){
		CAScheduler::getScheduler()->scheduleOnce([=](float interval){
			provinceView->selectRow(I, 0, true);
		}, "selectProvince", provinceView, 0);
	}
	//市
	cityView=CAPickerView::createWithLayout(DLayout(DHorizontalLayout_W_C(width, 0.5), DVerticalLayout_T_H(100, 400)));
	cityView->setFontSizeNormal(40);
	cityView->setBackgroundImage(CAImage::createWithColor4B(ccc4(190, 190, 190, 255)));
	cityView->onHeightForComponent([](unsigned int component){
		return 80;
	});
	cityView->onViewForSelected([](unsigned int component, DSize size){
		return CAView::createWithColor(themeColor);
	});
	cityView->onTitleForRow([=](unsigned int row, unsigned int component){
		return cityDatas[row]["name"].asCString();
	});
	cityView->onWidthForComponent([=](unsigned int component){
		return this->getView()->getBounds().size.width;
	});
	cityView->onNumberOfRowsInComponent([=](unsigned int component){
		return cityDatas.size();
	});
	cityView->onDidSelectRow([=](unsigned int row, unsigned int component){
		II=row;
		countyDatas=cityDatas[row]["children"];
		const char* province=provinceDatas[I]["name"].asCString();
		const char* city=cityDatas[row]["name"].asCString();
		const char* county=countyDatas[0]["name"].asCString();
		if(area.compare("receive")==0){
			receiveAreaCode=countyDatas[0]["id"].asUInt();
			receiveArea->setText(obj2str("%s%s%s", province, city, county));
		}else if(area.compare("areaName")==0){
			areaCode=countyDatas[0]["id"].asUInt();
			areaName->setText(obj2str("%s%s%s", province, city, county));
		}
		if(countyView!=nullptr){
			countyView->reloadAllComponents();
		}
	});
	subview->addSubview(cityView);
	if(II>0){
		CAScheduler::getScheduler()->scheduleOnce([=](float interval){
			cityView->selectRow(II, 0, true);
		}, "selectCity", cityView, 0);
	}
	//区
	countyView=CAPickerView::createWithLayout(DLayout(DHorizontalLayout_R_W(0, width), DVerticalLayout_T_H(100, 400)));
	countyView->setFontSizeNormal(40);
	countyView->setBackgroundImage(CAImage::createWithColor4B(ccc4(190, 190, 190, 255)));
	countyView->onHeightForComponent([](unsigned int component){
		return 80;
	});
	countyView->onViewForSelected([](unsigned int component, DSize size){
		return CAView::createWithColor(themeColor);
	});
	countyView->onTitleForRow([=](unsigned int row, unsigned int component){
		return countyDatas[row]["name"].asCString();
	});
	countyView->onWidthForComponent([=](unsigned int component){
		return this->getView()->getBounds().size.width;
	});
	countyView->onNumberOfRowsInComponent([=](unsigned int component){
		return countyDatas.size();
	});
	countyView->onDidSelectRow([=](unsigned int row, unsigned int component){
		const char* province=provinceDatas[I]["name"].asCString();
		const char* city=cityDatas[II]["name"].asCString();
		const char* county=countyDatas[row]["name"].asCString();
		if(area.compare("receive")==0){
			receiveAreaCode=countyDatas[row]["id"].asUInt();
			receiveArea->setText(obj2str("%s%s%s", province, city, county));
		}else if(area.compare("areaName")==0){
			areaCode=countyDatas[row]["id"].asUInt();
			areaName->setText(obj2str("%s%s%s", province, city, county));
		}
	});
	subview->addSubview(countyView);
	if(III>0){
		CAScheduler::getScheduler()->scheduleOnce([=](float interval){
			countyView->selectRow(III, 0, true);
		}, "selectCounty", countyView, 0);
	}
}